import os
import zipfile


def create_proxy_auth_extension(proxy_host, proxy_port, proxy_username, proxy_password):
    """创建更可靠的代理认证扩展"""
    manifest_json = """
    {
        "version": "1.0.0",
        "manifest_version": 2,
        "name": "Kuaidaili Proxy Auth",
        "permissions": [
            "proxy",
            "tabs",
            "unlimitedStorage",
            "storage",
            "<all_urls>",
            "webRequest",
            "webRequestBlocking"
        ],
        "background": {
            "scripts": ["background.js"]
        },
        "minimum_chrome_version": "22.0.0"
    }
    """

    background_js = f"""
    const config = {{
        mode: "fixed_servers",
        rules: {{
            singleProxy: {{
                scheme: "http",
                host: "{proxy_host}",
                port: parseInt({proxy_port})
            }},
            bypassList: ["localhost", "127.0.0.1", "::1"]
        }}
    }};
    chrome.proxy.settings.set({{value: config, scope: "regular"}}, function() {{}});

    // 处理认证请求
    chrome.webRequest.onAuthRequired.addListener(
        function handler(details) {{
            console.log('Proxy auth required for: ' + details.url);
            return {{
                authCredentials: {{
                    username: "{proxy_username}",
                    password: "{proxy_password}"
                }}
            }};
        }},
        {{urls: ["<all_urls>"]}},
        ['blocking']
    );

    // 监听代理错误
    chrome.proxy.onProxyError.addListener(function(details) {{
        console.error('Proxy error: ' + details.error);
    }});
    """

    # 创建扩展目录
    extension_dir = "proxy_auth_extension"
    os.makedirs(extension_dir, exist_ok=True)

    # 写入文件
    with open(os.path.join(extension_dir, "manifest.json"), "w", encoding="utf-8") as f:
        f.write(manifest_json)

    with open(os.path.join(extension_dir, "background.js"), "w", encoding="utf-8") as f:
        f.write(background_js)

    # 打包为crx（Chrome扩展格式）
    extension_path = f"{extension_dir}.zip"
    with zipfile.ZipFile(extension_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.write(os.path.join(extension_dir, "manifest.json"), "manifest.json")
        zf.write(os.path.join(extension_dir, "background.js"), "background.js")

    return extension_path
